package com.devicemantra.coordinate.operations;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import com.devicemantra.coordinate.dataobjects.CStateFactory;
import com.devicemantra.coordinate.dataobjects.ContactInfo;
import com.devicemantra.coordinate.dataobjects.Logo;

import com.devicemantra.coordinate.dataobjects.*;
import com.devicemantra.coordinate.exceptions.dataobjects.CDatabaseException;
import com.devicemantra.coordinate.exceptions.jaxb.CJAXBException;
import com.devicemantra.coordinate.exceptions.operations.CDepartmentAlreadyExistsException;
import com.devicemantra.coordinate.exceptions.operations.CException;
import com.devicemantra.coordinate.exceptions.operations.CFileParameterNotFoundException;
import com.devicemantra.coordinate.exceptions.operations.CIOException;
import com.devicemantra.coordinate.exceptions.operations.CParameterNotFoundException;
import com.devicemantra.coordinate.exceptions.operations.CReadPayloadException;
import com.devicemantra.coordinate.exceptions.operations.CStateAlreadyExistsException;
import com.devicemantra.coordinate.exceptions.operations.CStateDoesNotExistsException;
import com.devicemantra.coordinate.exceptions.operations.CWritePayloadException;
import com.devicemantra.coordinate.interfaces.http.CHttpReader;
import com.devicemantra.coordinate.interfaces.http.CHttpWriter;
import com.devicemantra.coordinate.jaxb.Department;
import com.devicemantra.coordinate.jaxb.JAXBRequestFactory;
import com.devicemantra.coordinate.jaxb.OperationType;
import com.devicemantra.coordinate.jaxb.Request;
import com.devicemantra.coordinate.jaxb.State;
import com.oreilly.servlet.multipart.FilePart;

public class AddDepartmentImpl implements COperation {
	
	private CResponseBuilder mResponseBuilder = null;
	private CRequestBuilder mRequestBuilder = null;
	private OperationType mOperationType = OperationType.ADD_DEPARTMENT;
	HttpServletRequest mHTTPRequest = null;
	HttpServletResponse mHTTPResponse = null;
	
	
	public AddDepartmentImpl() {
		mResponseBuilder = new CResponseBuilder();
	}

	@Override
	public String getResponse() {
		return null;
	}

	@Override
	public void processEvent(HttpServletRequest pHTTPRequest, 
			HttpServletResponse pHTTPResponse) throws CException {
		
		System.out.println("Operation executing - " + mOperationType);
		mHTTPRequest = pHTTPRequest;
		mHTTPResponse = pHTTPResponse;
		mRequestBuilder = new CRequestBuilder(mHTTPRequest);
		String lDeleteStateName = null;
		/* Optimistic setting of status code and response string */
		mResponseBuilder.setStatus(200, "Success Operation executed");
		try {
			mRequestBuilder.processFormFileEvent();
		}catch (CJAXBException e1) {			// TODO Auto-generated catch block
			mResponseBuilder.setStatus(500, "FATAL: JAXB Could not parse request :" );
			e1.printStackTrace();
			throw new CException(e1.getMessage());
		} catch (CParameterNotFoundException e) {
			mResponseBuilder.setStatus(500, "FATAL: Parameter not found" );
			e.printStackTrace();
			throw new CException(e.getMessage());
		} catch (CIOException e) {
			mResponseBuilder.setStatus(500, "FATAL: Could not read form data" );
			throw new CException(e.getMessage());
		}catch (CException e) /* Unsupported encoding */ {
			mResponseBuilder.setStatus(500, "FATAL: Unsupported encoding " );
			throw new CException(e.getMessage());
		} 
		
		OperationType lOpType = mRequestBuilder.getOperationType();
		
		if( mOperationType != lOpType ) {
			mResponseBuilder.setStatus(409, "CONFLICT ERROR: Request does not match Url : Request directed at " + lOpType + " Destination was " + mOperationType);
			throw new CException("ERROR: Request does not match Url : Request directed at " + lOpType + " Destination was " + mOperationType);
		}
		
		Request lRequest = mRequestBuilder.getRequestObj();
		Department lDept = lRequest.getCRequestData().getCDepartment();
		if( lDept != null ) {
			/*System.out.println("Department name is " + lDept.getCDepartmentInfo().getCDepartmentName());
			System.out.println("Department person name is " + lDept.getCDepartmentInfo().getCPersonName().getFirstName());
			System.out.println("Department Desc " + lDept.getCDepartmentInfo().getCDescription());
			System.out.println("Department Email is " + lDept.getCDepartmentInfo().getCEmailAddress());
			System.out.println("Department Desig is " + lDept.getCDepartmentInfo().getCPersonDesignation());
			System.out.println("Department Mobile is " + lDept.getCDepartmentInfo().getCMobileNumber()); */
		}
		FilePart lFile = null;
		try {
			lFile = mRequestBuilder.getFile("DEPT_LOGO_FILE");
		} catch (CFileParameterNotFoundException e) {
			mResponseBuilder.setStatus(500, "FATAL: Logo not found" );
			e.printStackTrace();
			throw new CException(e.getMessage());
		}
		
		System.out.println("File name is " + lFile.getFileName());
		System.out.println("File content is " + lFile.getContentType());
		System.out.println("File path is " + lFile.getFilePath());
		System.out.println("File name is " + lFile.getName()); 
		
		byte[] lFileInBytes = null;
		try {
			lFileInBytes = mRequestBuilder.getFileAsBytes("DEPT_LOGO_FILE");
		} catch (CFileParameterNotFoundException e) {
			e.printStackTrace();
			throw new CException(e.getMessage());
		}
		System.out.println("Bytes = " + lFileInBytes.length);
		Logo lLogo = new Logo(lFile.getFileName(),lFile.getContentType(),lFileInBytes);
		ContactInfo lContactInfo = new ContactInfo(lDept.getCDepartmentInfo().getCPersonName().getFirstName(),
				 lDept.getCDepartmentInfo().getCPersonDesignation()	,
				 lDept.getCDepartmentInfo().getCEmailAddress(),
				 lDept.getCDepartmentInfo().getCMobileNumber(),
				 null);
		try {
			CDepartmentFactory.createNewDepartment(	lDept.getCDepartmentInfo().getCDepartmentName(),
													lDept.getCDepartmentInfo().getCDescription(),
													lLogo,
													lContactInfo);
		} catch (CDepartmentAlreadyExistsException e) {
			mResponseBuilder.setStatus(420, "Department already exists." );
			e.printStackTrace();
			throw new CException(e.getMessage());
		}
		
		
		/*try {
			CStateFactory.deleteState(lDeleteStateName);
		} catch (CDatabaseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			mResponseBuilder.setStatus(500, "Database exception ");
		} catch (CStateDoesNotExistsException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			mResponseBuilder.setStatus(420, "State does not exist ");
		} */
		
	}

	@Override
	public void sendResponse() throws CException {
		try {
			CHttpWriter.writeAsString(mHTTPResponse, mResponseBuilder.getAsXML());
		} catch (CWritePayloadException e) {
			e.printStackTrace();
			mResponseBuilder.setStatus(420, "State Already Exists");
			throw new CException(e.getMessage());
		} catch (CException e) {
			e.printStackTrace();
			mResponseBuilder.setStatus(420, "State Already Exists");
			throw new CException(e.getMessage());
		}
			
	}

}
